package com.woniuxy.sale.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.commons.entity.sale.PackingList;
import com.woniuxy.commons.entity.sale.vo.sale.PackingListVo;
import com.woniuxy.commons.result.Result;
import com.woniuxy.commons.utils.PageUtils;
import com.woniuxy.sale.mapper.PackingListDao;
import com.woniuxy.sale.service.PackingListService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: CHL  <br/>
 * @ToDo: <br>
 * Date: 2022/4/19:14:43  <br/>
 * Description:
 */
@Service
public class PackingListServiceImpl implements PackingListService, InitializingBean {

    @Resource
    PackingListDao packingListDao;

    @Resource
    RedisTemplate<String, List<PackingList>> redisTemplate;

    @Override
    //将selectAll里面的所有key删除，以此实现redis的缓存一致性
    @CacheEvict(value = "selectAll", allEntries = true)
    public int insert(PackingList packingList) {
        return packingListDao.insert(packingList);
    }

    @Override
    //第一个参数：缓存名    key就是缓存的key
    //加了这个注解就说明这个方法的返回值（Result）是可以被缓存的
//    @PostConstruct
    @Cacheable(value = "selectAll", key = "#pageNum + ':' +#pageSize + ':' + #packingListVo.packingNumber")
    public Result selectAll(Integer pageNum, Integer pageSize, PackingListVo packingListVo) {
        //
        PageHelper.startPage(pageNum, pageSize, "id desc");
        List<PackingList> packingLists;
//        if (redisTemplate.opsForValue().get("packingList")==null){
        packingLists = packingListDao.selectAll(packingListVo);
//          redisTemplate.opsForValue().set("packingList",packingLists);
        //设置过期时间
//         }
//        packingLists = redisTemplate.opsForValue().get("packingList");
        PageInfo<PackingList> pageInfo = PageInfo.of(packingLists);
        //TODO 设置分页信息，返回分页对象
        PageUtils pageUtils = new PageUtils(pageInfo);
        return Result.ok(pageUtils);
    }

    /**
     * Description : TODO  用来判断key是否设置过并且还未过期
     * TODO 从redis中获取key对应的过期时间;
     *  * 如果该值有过期时间，就返回相应的过期时间;
     *  * 如果该值没有设置过期时间，就返回-1;
     *  * 如果没有该值，就返回-2;
     * ChangeLog : 1. 创建 (2022/4/25 13:12 [CHL]);
     * * @param key
     * *  @return boolean
     **/
    @Override
    public Long isExpire(String key) {
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }

    @Override
    public List<PackingList> selectBy(PackingList packingList) {
        return packingListDao.selectBy(packingList);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
